<!--  -->
<template>
  <div class="device-list flex-column h-100P">
    <!-- 查询条件 -->
    <div class="justify-start">
      <query-container style="padding:0 0 20px 0;" @search="handleSearch" @reset="handleReset">
        <el-form ref="queryForm" inline :model="queryInfo" label-position="left" label-width="80px">
          <el-form-item label="选择产品" prop="productId">
            <SelectProduct ref="SelectProduct" class="input" @change="({id})=>queryInfo.productId=id"/>
          </el-form-item>
          <el-form-item label="启用状态" prop="enableStateEnum">
            <SelectDeviceState class="input" v-model="queryInfo.enableStateEnum"/>
          </el-form-item>
          <el-form-item label="在线状态" prop="online">
            <SelectOnlineState ref="SelectOnlineState" class="input" v-model="queryInfo.online"/>
          </el-form-item>
          <el-form-item label="入网类型" prop="netType">
            <SelectNetType class="input" v-model="queryInfo.netType"/>
          </el-form-item>
          <el-form-item label="上线时间" prop="datetime">
            <el-date-picker
              v-model="queryInfo.datetime"
              unlink-panels
              type="daterange"
              value-format="timestamp"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="input"
              :default-time="['00:00:00','23:59:59']"
            />
          </el-form-item>
          <el-form-item label="关键词" prop="keyword">
            <el-input
              v-model="queryInfo.keyword"
              placeholder="请输入设备名或备注名称"
              clearable
              class="input"
            >
              <i slot="suffix" class="el-input__icon el-icon-search"/>
            </el-input>
          </el-form-item>
        </el-form>
      </query-container>
    </div>
    <!-- 添加按钮 -->
    <div class="flex">
      <CustomButton style="width: 152px;" title="添加设备至网关" @click="handleCreateGroup"/>
    </div>
    <!-- table -->
    <el-table
      v-loading="loading"
      :data="tableData"
      header-cell-class-name="table-header-cell"
      header-row-class-name="table-header-row"
      class="table-container flex-sub"
    >
      <el-table-column prop="name" label="设备名/备注名称">
        <template v-slot="{row:{name,remarkName}}">
          <div class="cell-style">
            <div style="color: #1E1E1E;">{{ name }}</div>
            <div>{{ remarkName }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="personName" label="所属产品">
        <template v-slot="{row:{productVo}}">
          <div class="cell-style">
            {{ productVo && productVo.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="入网类型">
        <template v-slot="{row:{productVo}}">
          <div class="cell-style">
            {{ productVo && productVo.netTypeName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="启用状态">
        <template v-slot="{row:{enableStateEnumName,enableStateEnum}}">
          <span :class="enableStateEnum">{{ enableStateEnumName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="在线状态">
        <template v-slot="{row:{online}}">
          <span class="online-state" :style="{color:( online?'#0084EE':'#D12D1F')}">
            {{ online ? '在线' : '离线' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="最近上线时间">
        <template slot-scope="scope">
          <span>{{ scope.row.activeTime | dateTimeFormatter }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <div class="justify-center">
            <div class="btn-delete" @click="handleDelete(scope.row.id)">从分组中移除</div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      hide-on-single-page
      background
      layout="prev, pager, next, total, jumper"
      :total="queryInfo.total"
      :page-size="queryInfo.pageSize"
      @current-change="handlePageNoChange"
    />
    <DeviceSelector
      :visible.sync="dialogVisible"
      :config="{title:'添加设备至网关',confirmButtonText:'添加',cancelButtonText:'取消',excludeBusinessTypeEnum:'GATEWAY'}"
      @confirm="handleAddDeviceIntoGroup"
    />
    <!--    <player-dialog :url="playerUrl" :dialog-visible="isShowPlayer" @close="isShowPlayer = false" />-->
  </div>
</template>

<script>
import { apiFindDevicePageByParam } from '@/views/device/deploy-device/api'
import SelectProduct from '@/views/device/create-product/components/select-product'
import SelectDeviceState from '@/views/device/deploy-device/components/select-device-state'
import SelectOnlineState from '@/views/device/deploy-device/components/select-device-online-state'
import SelectNetType from '@/views/device/deploy-device/components/select-net-type'
import DeviceSelector from '@/components/device-selector/index'
import { apiAddGatewayDevice, apiDelGatewayDevice } from '../api'
import CustomButton from '@/components/custom-button'
import QueryContainer from '@/components/query-container'

export default {
  name: 'DeployDevice',
  components: {
    CustomButton,
    SelectProduct,
    SelectOnlineState,
    SelectDeviceState,
    SelectNetType,
    DeviceSelector,
    QueryContainer
  },

  data() {
    return {
      dialogVisible: false,
      queryInfo: {
        /**
         * @type {'EXTERNAL','INTERNAL'} deviceSourceEnum
         */
        deviceSourceEnum: 'INTERNAL',
        // 在线状态
        online: '',
        // 启用状态
        enableStateEnum: '',
        // 所属产品id
        productId: '',
        // 所属网关id,
        gatewayId: '',
        // 入网类型
        netType: '',
        keyword: '',
        dateTime: null,
        pageSize: 10,
        pageNo: 1,
        total: 0
      },
      tableData: [],
      loading: false,
      isShowPlayer: false,
      // 设备控制弹窗
      deviceDialogVisible: false
    }
  },

  computed: {},

  created() {
    this.init()
  },
  methods: {
    init() {
      this.queryInfo.gatewayId = this.$route.query.id || ''
      this.findDevicePageByParam(this.queryInfo)
    },
    handlePageNoChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.handleSearch()
    },
    handleSearch() {
      this.findDevicePageByParam(this.queryInfo)
    },
    handleReset() {
      this.$refs.queryForm.resetFields()
      this.$refs.SelectProduct.handleReset()
      this.$refs.SelectOnlineState.handleReset()
      this.handleSearch()
    },
    handleCreateGroup() {
      this.dialogVisible = true
    },
    handleEdit(device) {
      this.$router.push({ path: '/device/deploy-device-detail', query: { deviceId: device.id } })
    },
    async findDevicePageByParam(queryInfo) {
      this.loading = true
      if (queryInfo.deviceSourceEnum && !queryInfo.deviceSourceEnum.length) {
        queryInfo.deviceSourceEnum = undefined
      }
      const formData = {}
      for (const key in this.queryInfo) {
        if (this.queryInfo[key] && this.queryInfo[key].toString().length) {
          formData[key] = this.queryInfo[key]
        }
      }
      const { records, total } = await apiFindDevicePageByParam(formData)
      this.tableData = records
      this.queryInfo.total = total
      this.loading = false
    },
    handleAddDeviceIntoGroup(devices) {
      const groupDeviceList = devices.map(device => ({
        gatewayId: this.queryInfo.gatewayId,
        deviceId: device.id
      }))
      apiAddGatewayDevice(groupDeviceList).then(() => {
        this.$message.success('添加设备到分组成功')
        this.handleSearch()
        this.listenChange()
      })
    },
    handleDelete(deviceId) {
      this.$confirm('确定要将该设备从分组中移除吗？', '从分组中移除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        apiDelGatewayDevice({ gatewayId: this.queryInfo.gatewayId, deviceId }).then(() => {
          this.$message.success('移除设备成功')
          this.handleSearch()
          this.listenChange()
        })
      })
    },
    listenChange() {
      this.$emit('change')
    }
  }
}
</script>
<style lang="scss" scoped>
.device-list {
  width: 100%;
  height: 100%;
  background: #fff;
  box-sizing: border-box;

  .input {
    width: vw(350px);
  }

  .ENABLE {
    color: #0084ee;
  }

  .DISABLE {
    color: #f6a326;
  }

  .OFFLINE,
  .ONLINE {
    position: relative;

    &::after {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin-left: 10px;
      border-radius: 50%;
      content: '';
    }
  }

  .ONLINE {
    &::after {
      background-color: #67c23a;
    }
  }

  .OFFLINE {
    &::after {
      background-color: #909399;
    }
  }

  .summery {
    height: 40px;
    border-radius: 4px;
    box-shadow: -1px 0 4px 0 rgba(29, 29, 29, 0.15);

    & > div {
      &:not(:last-child)::after {
        display: inline-block;
        width: 1px;
        height: 100%;
        background: linear-gradient(
            0deg,
            rgba(255, 255, 255, 0) 0%,
            rgba(153, 153, 153, 0.5) 26%,
            rgba(153, 153, 153, 0.99) 53%,
            rgba(153, 153, 153, 0.44) 79%,
            #fff 100%
        );
        content: '';
      }
    }

    .value {
      color: #0084ee;
    }
  }

  ::v-deep .el-form-item {
    margin-bottom: 20px;
  }

  .cell-style {
    color: #999;
  }
}

.query-container {
  display: flex;
  flex-direction: row;
}

.btn-edit {
  color: #0084ee;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}

.btn-delete {
  color: #0084ee;

  &:hover {
    cursor: pointer;
    opacity: 0.7;
  }
}
</style>
